<script setup lang="ts">
  import OperateLog from './components/OperateLog.vue'
  import ReturnFactoryInfo from './components/ReturnFactoryInfo.vue'
  import GoodList from './components/good-list/Index.vue'
  import LogisticsList from './components/logistics-list/Index.vue'
  import { computed, CSSProperties, nextTick, onMounted, ref } from 'vue'
  import routeComponentName from '@/config/route-component-name'
  import {
    useGetReturnFactoryDetail,
    useGetDetailCustomFieldById,
    useGetReturnFactoryModuleCheckSet,
  } from '@/services/pages/return-factory/useReturnFactory'
  import { useRoute } from 'vue-router'
  import useRepairGoodListShareData from './composables/useRepairGoodListShareData'
  import SendGoodList from './components/send-good-list/index.vue'
  import { HMessageBox } from '@/components/common/message'
  import CheckGoodModal from './components/check-good-modal.vue'
  import LogisticsFillModal from './components/logistics-fill-modal.vue'
  import ActualCollectPostingModal from './components/actual-collect-posting-modal.vue'

  const { setRepairGoodList } = useRepairGoodListShareData()
  const { detail, getDetailLoading, getDetail } = useGetReturnFactoryDetail()
  const {
    customFieldList,
    loading: getDetailCustomFieldLoading,
    getCustomField,
  } = useGetDetailCustomFieldById()
  const {
    loading: getReturnFactoryModuleCheckSetLoading,
    returnFactoryCheckSet,
    getSet: getReturnFactoryModuleCheckSet,
  } = useGetReturnFactoryModuleCheckSet()

  defineOptions({
    name: routeComponentName.returnFactory.returnFactoryDetail,
  })

  const goodCheckModalVisible = ref(false)
  const logisticsFillInModalVisible = ref(false)
  const actualCollectPostingModalVisible = ref(false)

  const route = useRoute()

  const sidebarIsExpand = ref(true)

  const operateLogInstance = ref<InstanceType<typeof OperateLog> | null>(null)
  const goodListInstance = ref<InstanceType<typeof GoodList> | null>(null)
  const logisticsListInstance = ref<InstanceType<typeof LogisticsList> | null>(null)
  const sendGoodListInstance = ref<InstanceType<typeof SendGoodList> | null>(null)

  const selectedGoods = ref<Array<ReturnFactoryDetailGood>>([])

  const bodyStyle = computed<CSSProperties>(() => {
    return {
      paddingTop: '0px',
      paddingBottom: '0px',
      paddingLeft: '12px',
      paddingRight: sidebarIsExpand.value ? '0' : '24px',
    }
  })

  const sidebarExpandBtnStyle = computed<CSSProperties>(() => {
    if (sidebarIsExpand.value) {
      return {
        borderTopRightRadius: '3px',
        borderBottomRightRadius: '3px',
        borderTopLeftRadius: '0px',
        borderBottomLeftRadius: '0px',
      }
    }

    return {
      borderTopLeftRadius: '3px',
      borderBottomLeftRadius: '3px',
      borderTopRightRadius: '0px',
      borderBottomRightRadius: '0px',
    }
  })

  const returnFactoryInformation = computed(() => {
    return {
      no: detail.value.repairNo || '',
      createTime: detail.value.createTime,
      source: detail.value.source,
      customerService: detail.value.emp || '',
      faultType: detail.value.faultDescr,
      desc: detail.value.repairDescr,
      imgList: detail.value.images,
      enableNetwork: detail.value.enableNetwork,
      network: detail.value.network,
    }
  })

  const loading = computed(() => {
    return (
      getDetailLoading.value ||
      getDetailCustomFieldLoading.value ||
      getReturnFactoryModuleCheckSetLoading.value
    )
  })

  const onChangeSideBarVisible = () => {
    sidebarIsExpand.value = !sidebarIsExpand.value
    nextTick(() => {
      if (sidebarIsExpand.value && operateLogInstance.value) {
        operateLogInstance.value.getList()
      }
    })
  }

  const handleSelectGood = (goods: Array<ReturnFactoryDetailGood>) => {
    selectedGoods.value = goods
  }

  /**
   * 物流更新事件
   */
  // const handleLogisticsUpdate = async () => {
  //   getDetail(route.params.id as string)
  //   getOperateLog()
  //   getGoodList()
  // }

  const getOperateLog = async () => {
    if (operateLogInstance.value) {
      await operateLogInstance.value.getList()
      sidebarIsExpand.value = operateLogInstance.value.total > 0
    }
  }

  const getLogisticsList = () => {
    if (logisticsListInstance.value) {
      logisticsListInstance.value.getList()
    }
  }

  const getGoodList = async () => {
    if (goodListInstance.value) {
      await goodListInstance.value.getList()
      setRepairGoodList(goodListInstance.value.goodList)
    }
  }

  const getSendGoodList = () => {
    if (sendGoodListInstance.value && [10, 11, 6, 7].includes(detail.value.status)) {
      sendGoodListInstance.value.getList()
    }
  }

  const onGoodListUpdate = () => {
    getDetail(route.params.id as string)
    getOperateLog()
    getLogisticsList()
    getSendGoodList()
    getGoodList()
  }

  const onCheckClick = async () => {
    if (returnFactoryCheckSet.value === 2 && selectedGoods.value.length <= 0) {
      HMessageBox.error('请选择产品')
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 0)) {
      HMessageBox.error('只能选择待审核的产品')
      return
    }

    goodCheckModalVisible.value = true
  }

  const onFillLogistics = async () => {
    if (returnFactoryCheckSet.value === 2 && selectedGoods.value.length === 0) {
      HMessageBox.error('请选择产品')
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 1)) {
      HMessageBox.error('只能选择待返厂的产品')
      return
    }

    logisticsFillInModalVisible.value = true
  }

  const init = async () => {
    if (route.params.id) {
      await getDetail(route.params.id as string)
      getCustomField(route.params.id as string)
      getReturnFactoryModuleCheckSet(route.params.id as string)
      getOperateLog()
      getGoodList()
      getSendGoodList()
      if ([2, 3].includes(detail.value.status)) {
        getLogisticsList()
      }
    }
  }

  const onActualCollectPostingClick = () => {
    if (goodListInstance.value) {
      setRepairGoodList(goodListInstance.value.goodList)
    }
    actualCollectPostingModalVisible.value = true
  }

  onMounted(() => {
    init()
  })
</script>

<template>
  <div v-loading="loading" class="return-factory-detail-wrapper">
    <div class="return-factory-detail">
      <div class="header">
        <div class="title-wrapper">
          <i class="iconfont icon-detail"></i>
          <div class="title">返厂单号：</div>
          <div class="return-factory-code">{{ detail.repairNo }}</div>
          <h-status v-if="detail.status === 1" type="warning">待审核</h-status>
          <h-status v-if="detail.status === 2" type="warning">待返厂</h-status>
          <h-status v-if="detail.status === 3" type="warning">待签收</h-status>
          <h-status v-if="detail.status === 4">处理中</h-status>
          <h-status v-if="detail.status === 5" type="warning">待寄回</h-status>
          <h-status v-if="detail.status === 6" type="warning">待签收</h-status>
          <h-status v-if="detail.status === 7" type="success">已完成</h-status>
          <h-status v-if="detail.status === 8" type="info">已取消</h-status>
          <h-status v-if="detail.status === 9" type="warning">实收未过账</h-status>
          <h-status v-if="detail.status === 10" type="warning">待发货</h-status>
          <h-status v-if="detail.status === 11" type="warning">实发未过账</h-status>
        </div>
        <div class="btn-group">
          <!-- 先隐藏，后面会用到 -->
          <!-- <el-dropdown trigger="click">
        <h-button>
          确认处理方式
          <el-icon>
            <arrow-down></arrow-down>
          </el-icon>
        </h-button>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>退货</el-dropdown-item>
            <el-dropdown-item>换货</el-dropdown-item>
            <el-dropdown-item>生成工单</el-dropdown-item>
            <el-dropdown-item>寄回</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
          <!-- <h-plain-button
            v-if="detail.status === 1"
            v-permission="'retrunFactory_check'"
            type="warning"
            @click="onCheckClick"
          >
            审核
          </h-plain-button> -->
          <h-plain-button
            v-if="detail.status === 2 && detail.btnEventType === 1"
            v-permission="'retrunFactory_logistics'"
            @click="onFillLogistics"
          >
            填写返厂物流
          </h-plain-button>
          <h-plain-button v-if="detail.status === 9" @click="onActualCollectPostingClick">
            实收过账
          </h-plain-button>
        </div>
      </div>
      <div class="top-divider"></div>
      <div class="body" :style="bodyStyle">
        <div class="main">
          <div class="info-wrapper">
            <!-- 公司寄出信息 -->
            <div class="customer-info">
              <div class="title">寄出信息</div>
              <div class="info-list">
                <div class="info-item">
                  <div class="label">客户姓名:</div>
                  <div class="value">{{ detail.username }}</div>
                </div>
                <div class="info-item">
                  <div class="label">联系人:</div>
                  <div class="value">{{ detail.contacts }}</div>
                </div>
                <div class="info-item">
                  <div class="label">联系人手机号:</div>
                  <div class="value">{{ detail.phone }}</div>
                </div>
                <div class="info-item">
                  <div class="label">客户地址:</div>
                  <div class="value">
                    {{ detail.province }} {{ detail.city }} {{ detail.area }} {{ detail.address }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 公司收货信息 -->
            <div class="service-report">
              <div class="title">收货信息</div>
              <div class="info-list">
                <div class="info-item">
                  <div class="label">取件方式:</div>
                  <div class="value">{{
                    detail.receiveAddrVo.customerTakePieceMode === 1 ? '自取' : '快递寄回'
                  }}</div>
                </div>
                <div class="info-item">
                  <div class="label">收货人姓名:</div>
                  <div v-if="detail.receiveAddrVo.customerTakePieceMode !== 1" class="value">
                    {{ detail.receiveAddrVo.customerReceiveUsername }}
                  </div>
                </div>
                <div class="info-item">
                  <div class="label">收货手机:</div>
                  <div v-if="detail.receiveAddrVo.customerTakePieceMode !== 1" class="value">{{
                    detail.receiveAddrVo.customerReceivePhone
                  }}</div>
                </div>
                <div class="info-item">
                  <div class="label">收货地址:</div>
                  <div v-if="detail.receiveAddrVo.customerTakePieceMode !== 1" class="value">
                    {{ detail.receiveAddrVo.customerReceiveProvince }}
                    {{ detail.receiveAddrVo.customerReceiveCity }}
                    {{ detail.receiveAddrVo.customerReceiveArea }}
                    {{ detail.receiveAddrVo.customerReceiveAddress }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 返厂信息 -->
          <div class="base-info">
            <return-factory-info
              :return-factory-info="returnFactoryInformation"
              :custom-field-list="customFieldList"
            />
          </div>

          <!-- 返厂清单 -->
          <div class="return-factory-goods">
            <good-list
              ref="goodListInstance"
              :detail="detail"
              :module-check-method="returnFactoryCheckSet"
              @select-good="handleSelectGood"
              @update="onGoodListUpdate"
            />
          </div>

          <div v-if="[10, 11, 6, 7].includes(detail.status)" class="repair-sended-good-list">
            <send-good-list
              ref="sendGoodListInstance"
              :repair-detail="detail"
              @update="onGoodListUpdate"
            />
          </div>

          <!-- 物流信息 -->
          <!-- 先隐藏，后续可能会用到 -->
          <!-- <div class="return-factory-logistics">
            <logistics-list
              ref="logisticsListInstance"
              :return-factory-id="(route.params.id as string) || ''"
              :module-check-method="returnFactoryCheckSet"
              :status="detail.status"
              @update="handleLogisticsUpdate"
            ></logistics-list>
          </div> -->
        </div>
        <div :class="{ 'expand-shrink-btn-wrapper': true, 'sidebar-expand': !sidebarIsExpand }">
          <div
            v-if="sidebarIsExpand"
            class="btn-inner"
            :style="sidebarExpandBtnStyle"
            @click="onChangeSideBarVisible"
          >
            <i class="iconfont icon-retract"></i>
          </div>

          <div
            v-else
            class="btn-inner"
            :style="sidebarExpandBtnStyle"
            @click="onChangeSideBarVisible"
          >
            <i class="iconfont icon-expand"></i>
          </div>
        </div>
        <div v-if="sidebarIsExpand" class="sidebar">
          <operate-log
            ref="operateLogInstance"
            :return-factory-id="(route.params.id as string) || ''"
          />
        </div>
      </div>
    </div>

    <check-good-modal
      v-model:visible="goodCheckModalVisible"
      :return-factory-id="detail.id"
      :check-method="returnFactoryCheckSet"
      :goods="selectedGoods"
      @check-success="init"
    />

    <logistics-fill-modal
      v-model:visible="logisticsFillInModalVisible"
      :check-method="returnFactoryCheckSet"
      :return-factory-id="detail.id"
      :selected-logistics-list="selectedGoods"
      @update="init"
    />

    <actual-collect-posting-modal
      v-model="actualCollectPostingModalVisible"
      :repair-id="detail.id"
      @update="init"
    />
  </div>
</template>

<style scoped lang="scss">
  @media screen and (max-width: 1570px) {
    .customer-send-receipt-info {
      width: 700px !important;
      flex-direction: row !important;
      column-gap: 48px;

      .customer-info,
      .service-report {
        flex: 1;
      }
    }
  }

  .return-factory-detail-wrapper {
    height: calc(100vh - 92px);
    width: 100%;
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    // 这个定位是用于让侧边栏的展开按钮放到最右边
    position: relative;

    .return-factory-detail {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      display: flex;
      flex-direction: column;

      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title-wrapper {
          display: flex;
          align-items: center;
          column-gap: 5px;
          font-size: 14px;

          .iconfont {
            color: $primaryColor;
          }

          .title {
            font-weight: bold;
          }
        }

        .btn-group {
          display: flex;
          column-gap: 5px;
        }
      }

      .top-divider {
        border-bottom: 1px dotted #e5e5e5;
        margin: 12px 0;
      }

      .body {
        flex: 1;
        display: flex;
        height: 0;
        background-color: #fff;
        box-sizing: border-box;

        .main {
          flex: 1;
          box-sizing: border-box;
          width: 0;
          display: flex;
          flex-direction: column;
          row-gap: 48px;
          overflow: auto;

          &::-webkit-scrollbar {
            display: none;
          }

          .info-wrapper {
            display: flex;
            column-gap: 100px;
            flex-wrap: wrap;
            row-gap: 48px;

            .customer-send-receipt-info {
              display: flex;
              flex-direction: column;
              row-gap: 24px;
              width: 300px;
            }

            .base-info {
              flex: 1;
            }

            .customer-info {
              display: flex;
              flex-direction: column;
              row-gap: 6px;

              .title {
                font-size: 12px;
                font-weight: bold;
                padding-left: 6px;
                border-left: 3px solid $primaryColor;
              }

              .info-list {
                padding: 0 0 0 9px;
                display: flex;
                row-gap: 4px;
                flex-wrap: wrap;
                column-gap: 64px;
                flex-direction: column;

                .info-item {
                  display: flex;
                  column-gap: 5px;

                  .label {
                    min-width: 74.89px;
                    max-width: 74.89px;
                    text-align: right;
                    color: #606266;
                    white-space: nowrap;
                  }
                }
              }
            }

            .service-report {
              display: flex;
              flex-direction: column;
              row-gap: 6px;

              .title {
                padding-left: 6px;
                border-left: 3px solid $primaryColor;
                font-size: 12px;
                font-weight: bold;
              }

              .info-list {
                padding: 0 0 0 9px;
                display: flex;
                flex-wrap: wrap;
                column-gap: 48px;
                row-gap: 4px;
                flex-direction: column;

                .info-item {
                  display: flex;
                  column-gap: 5px;

                  .label {
                    min-width: 62.89px;
                    max-width: 62.89px;
                    text-align: right;
                    color: #606266;
                    white-space: nowrap;

                    div {
                      width: 3px;
                    }
                  }
                }
              }
            }
          }
        }

        .expand-shrink-btn-wrapper {
          height: 100%;
          border-left: 1px dotted #e5e5e5;
          box-sizing: border-box;
          margin: 0 4px 0 24px;
          color: $primaryColor;
          display: flex;
          align-items: center;

          .btn-inner {
            background-color: #f1f6fc;
            width: 16px;
            height: 64px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s ease-in;

            .iconfont {
              font-size: 14px;
            }

            &:hover {
              background-color: $primaryColor;

              .iconfont {
                color: #fff;
              }
            }
          }
        }

        .sidebar-expand {
          border: none;
          position: absolute;
          right: 4px;
          top: 0;
          transform: translate(-50%, 0);
          box-sizing: border-box;
          margin: 0;
        }

        .sidebar {
          min-width: 360px;
          max-width: 360px;
          transition: all 0.3s ease-in;
          overflow: hidden;
        }
      }
    }
  }
</style>
